package net.pimpas.web.tests.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.pimpas.web.tests.auth.login.LoginUtils;

public class AuthenticateFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(request instanceof HttpServletRequest) {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			if(httpRequest.getRequestURI().equals("/login.faces"))
				// do normal
				chain.doFilter(request, response);
			else {
				Object ob = httpRequest.getSession(true).getAttribute(LoginUtils.USER_KEY);
				if(ob == null) {
					// user not logged in
					HttpServletResponse httpResponse = (HttpServletResponse) response;
					httpResponse.sendRedirect("/login.faces");
				}
				else
					// do normal
					chain.doFilter(request, response);
			}
		} else
			// do normal
			chain.doFilter(request, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}
}